const monday = document.getElementById('monday');
const tuesday = document.getElementById('tuesday');
const wednesday = document.getElementById('wednesday');
const thursday = document.getElementById('thursday');
const friday = document.getElementById('friday');
const saturday = document.getElementById('saturday');
const sunday  = document.getElementById('sunday');
// 以上获取栏条
const button = document.getElementsByTagName('button')
let left = 0;
let width = 0;
let item = document.createElement('div') ;
//let mondayItemList = [];
let drawing = false;// 开始画图事件为false
//let mondaySlot = [];// 记录位置是否有滑块，有滑块时不提供画图操作，限定移动边界 0 无 1 有;
let slotSize = 1448;
let adjustValue = 0; // 位置矫正值
let blockLeft = 0;; // 记录当前拖动滑块的左边边界，用于拖动时判断左右移动方向： e.clientX - adjust > blockLeft 右移，反之左移
let stopPos = -1; // 记录禁止再移动的值，如果一个滑块一直往左移动，最终位置为stopPos
let clickPostion = 0;
let moveLeft = true; // 记录移动方向

let tuesdaySlot = []
let tuesItemList = [];

// 初始化7个slot
let monSlot = [];
let tueSlot = [];
let wedSlot = [];
let thurSlot = [];
let friSlot = [];
let satSlot = [];
let sunSlot = [];
emptifySlot(monSlot);
emptifySlot(tueSlot);
emptifySlot(wedSlot);
emptifySlot(thurSlot);
emptifySlot(friSlot);
emptifySlot(satSlot);
emptifySlot(sunSlot);

// 初始化7个item列表
let monList = [];
let tueList = [];
let wedList = [];
let thurList = [];
let friList = [];
let satList = [];
let sunList = [];


// 7条绑定监听事件

function bindDayListner(dom,slot,list){
    // 开始事件
    dom.addEventListener('click', (event) =>mouseClick( event,dom,slot,list),false);
    // 诊断鼠标位置偏移使用
    dom.addEventListener('mousedown', (e)=>{
        console.log("mouseDow按下的鼠标位置",e.clientX);
        //console.log("当前所在的dom",dom);// 确认ok
    });
}

bindDayListner(monday,monSlot,monList);
bindDayListner(tuesday,tueSlot, tueList);
bindDayListner(wednesday,wedSlot,wedList);
bindDayListner(thursday,thurSlot,thurList);
bindDayListner(friday,friSlot,friList);
bindDayListner(saturday,satSlot,satList);
bindDayListner(sunday,sunSlot,sunList);


   /*// 开始事件
    monday.addEventListener('click', mouseClick,false);
    // 诊断鼠标位置偏移使用
    monday.addEventListener('mousedown', (e)=>{
        console.log("按下的鼠标位置",e.clientX)
    });

     tuesday.addEventListener('click', mouseClick,false);
    // 诊断鼠标位置偏移使用
    tuesday.addEventListener('mousedown', (e)=>{
        console.log("按下的鼠标位置",e.clientX)
    });*/


    function mouseMove(e) {
        // 没开始画时不触发事件改变width
        if(!drawing){
            return;
        }

        var e = e||event;
        width = e.clientX - left;
        //console.log('move',width);
         //console.log('当前鼠标位置',e.clientX);
        // item.style = `background:#ff461f;width:${width}px;height:36px;position:absolute; left:${left}px;`;
        item.style = `background:#ff461f;width:${width}px;height:36px;position:absolute; left:${left}px;`;
    }

    function mouseClick(e,dom,slot,list) {
        console.log('the mouse click');
        clickPostion = e.clientX;
        // 判断点击的位置是否有滑块
        
        // console.log('mondaySlot',mondaySlot)
        // console.log('鼠标单击的位置',clickPostion)
        // console.log('drawing',drawing);
        //var index = mondaySlot[clickPostion];
        var index = slot[clickPostion];
        console.log('click 的位置',index);
        if(index != -1){
        console.log('当前点击的item', index);
            // 当前位置有滑块，不画图
            console.log('在滑块上click，不画图,鼠标位置', clickPostion);
            // console.log(mondaySlot);
            console.log(slot);
            // 把滑块的时间坐标信息取出来
            // var itemNow = mondayItemList[index];
            var itemNow = list[index];
            var leftNow = itemNow.offsetLeft;
            var widthNow = itemNow.offsetWidth;
            // 转成时间
            var startTime = transToTime(leftNow);

            var endTime = transToTime(leftNow + widthNow);

            console.log('起点：' + leftNow + ' :width:' + widthNow);
            return;
        }

        // 开始画图
        if(!drawing) {
            //monday.addEventListener('mousemove', mouseMove,false);
            dom.addEventListener('mousemove', mouseMove,false);
            drawing = true;
            // 创建对象
            var e = e||event;
            left = e.clientX;
            // console.log('drawingClick left', left)
            item.setAttribute('draggable', true);
            // console.log('创建对象前list数量',mondayItemList.length);
            // mondayItemList.push(item);
            list.push(item);
            // console.log('创建对象push后list数量',mondayItemList.length);
            // monday.appendChild(item);
            dom.appendChild(item);
            item.style = `background:#ff461f;width:${width}px;height:36px;position:absolute; left:${left}px;`
            return;
        } 

        

        // console.log('第二次单击');
        // console.log('mondaySlot',mondaySlot);
        // console.log('结束画图时mondayItemList');
        //listItem(mondayItemList);
        // 第二次click时移除事件
        drawing = false;
        // monday.removeEventListener('mousemove',mouseMove,false);
        dom.removeEventListener('mousemove',mouseMove,false);
        // 保存对象
        // mondayItemList.push(item);
        // 绑定拖动事件
        bindDragevent(item,dom,slot,list);
        //emptifySlot(mondaySlot);

        // 保存位置信息至slot  画完不能再这里添加，只能在每次拖动结束后统一处理所有的item填充slot
        // savePosition(mondayItemList);
        savePosition(slot,list);
        //saveItemPosition(item,mondaySlot);

        // 再次初始化
        item = document.createElement('div') ;
        left = 0;
        width= 0;
    
    }













    // 添加对象的拖动事件
    function bindDragevent(item,dom,slot,list){


        // 绑定双击删除时间
        item.addEventListener('dblclick', (e)=> {
            // 删除元素
            dom.removeChild(item);
            // 清理数组--记得重新赋值
            list = removeItem(item,list);
            // 整理坐标数据
            savePosition(slot,list);
        })

        // console.log('item',item);
        // console.log('itemWidth',item.offsetWidth);
        // console.log('itemLeft',item.offsetLeft)
        // 不出现复制图片
        item.addEventListener('dragstart', (e)=> {
            //console.log('start', e);
            // e.dataTransfer.dropEffect
            // 记录拖动开始前的原始位置
            blockLeft = item.offsetLeft;
            console.log('原始位置', blockLeft)
            adjustValue = e.clientX - blockLeft;
            console.log('当前矫正值：',adjustValue);
            const img = new Image();
            img.style ="display:none;"
            e.dataTransfer.setDragImage(img, 10, 10);
            e.dataTransfer.effectAllowed = "move"
        });



        // 拖动进行中

        item.addEventListener('drag', (e)=>{
            // console.log('dragend', e)
            let solidWidth = item.offsetWidth;
            // left不能直接等于鼠标的位置，需要进行矫正，即鼠标单击时的位置与left 的差值 left = e.clientX - (fixLenth)
            leftNew = e.clientX - adjustValue;
            if(leftNew < 0) {
                // 处理画面闪烁问题
                console.log('return 0');
                leftNew = 0;
                return;
            }

            if(leftNew < blockLeft) {
                console.log('左移动');
                moveLeft = true;
                //console.log(mondaySlot);
                // 取最靠近的左边占位的pos 不能再挪动的位置
                if(stopPos == -1) {
                    stopPos = getOccupyLeft(blockLeft, slot);
                }
            } else {
                moveLeft = false;
                console.log('右移动');
                // 每次向右移动都需要更新最大右
                stopPos = getOccupyRight(blockLeft,solidWidth, slot);
            }
            console.log('拖动中鼠标位置:', e.clientX + '--拖动中的left' + leftNew)
            e.dataTransfer.dropEffect = "move"
            
            // 判断当前位置是否有元素，如果有元素则不让其再移动
            var startPos = leftNew;
            var endPos = startPos + solidWidth;
            
            item.style = `background:#ff461f;width:${solidWidth}px;height:36px;position:absolute; left:${leftNew}px;`;

        })

      

        item.addEventListener('dragend', (e)=>{
            // console.log('dragend', e)
            let solidWidth = item.offsetWidth;
            // left不能直接等于鼠标的位置，需要进行矫正，即鼠标单击时的位置与left 的差值 left = e.clientX - (fixLenth)
            leftNew = e.clientX - adjustValue;
            /*if(leftNew < 0) {
                leftNew = 0;
            }*/
            console.log('当前位置结束位置' + leftNew);

            console.log('拖动结束stopPos' + stopPos + "处理前left  " + leftNew)
            // 停下时判断位置，不能小于停止时的值-左边ok
            if(moveLeft && leftNew < stopPos){
                leftNew = stopPos;
            }

            // 右移动
            if(!moveLeft && leftNew > stopPos){
                leftNew = stopPos;
            }

            e.dataTransfer.dropEffect = "move"
            console.log('拖动结束的left', leftNew)
            // 如果是0 则添加添加8px 的边界
            if(leftNew <= 8) {
                console.log("+8")
                leftNew = leftNew + 8;
            }
            item.style = `background:#ff461f;width:${solidWidth}px;height:36px;position:absolute; left:${leftNew}px;`;
            // console.log('拖动结束时');
            listItem(list);
            savePosition(slot,list);
            console.log(slot);
            // 拖动结束，stopPos 归零
             stopPos = -1;
        })
    }

    // 添加对象的拖动事件
    function savePosition(slot,list){

        // 先清空以前的
       /* mondaySlot = [];
        for (i = 0; i < slotSize; i++) { 
            // 占空间
            mondaySlot[i] = 0;
        }*/

        emptifySlot(slot);
        // console.log('清空再填充');
        // console.log(mondayItemList.length);
        var len = list.length;
        // console.log('listLen',len);


        list.forEach((item, index)=> {
            // console.log('list数量',index);
            saveItemPosition(index,item,slot);
        })

        
        // console.log('mondaySlot',mondaySlot);
    }

    // 保存每一个元素的位置 index 之元素位置
    function saveItemPosition(index,item,slot){
        // console.log('itemWidth',item.offsetWidth);
        // console.log('itemWidth',item.offsetLeft);
        // 范围区间
        let length = item.offsetWidth;
        // 其实索引
        let startIndex = item.offsetLeft;

        for (i = 0; i < length; i++) { 
            // 占空间
            slot[startIndex + i] = index;
        }

        /*for (i = 0; i < slot.length; i++) { 
            // 占空间
            // console.log(slot[i]);
        }*/
    }

    function emptifySlot(slot){

        for (i = 0; i < slotSize; i++) { 
            // 占空间 -1 表示没有元素
            slot[i] = -1;
        }
    }

    function listItem(list) {
        // console.log('listItem')
        for (i = 0; i < list.length; i++) { 
            // 占空间
            // console.log(mondayItemList[i])
        }
    }

    function removeItem(destItem,list){
        var ret =  list.filter(item =>{
                return item != destItem
        })

        console.log(ret);
        return ret;
    };

    // 取左边最近的占位 blockLeft: 当前位置 targetSlot 对象查找的slot
    function getOccupyLeft(blockLeft, targetSlot){
        // 找值不为-1的index
        console.log('查找blockLeft 附近的'+ blockLeft)
        for (i = blockLeft - 1; i >= 0; i--) { 
            // 占空间
            if(targetSlot[i] > -1) {
                console.log('左边最近占位', i + 1);
                return i + 1;
            }


        }
        console.log('左边最近占位', 0);
        return 0;
        
    }

    // 取右边最近的占位 blockLeft: 当前位置 targetSlot 对象查找的slot
    function getOccupyRight(blockLeft, solidWidth,targetSlot){
        // 找值不为-1的index 不要直接代入当前值 + 1 
        var index = blockLeft + solidWidth;
        for (i = index + 1; i < targetSlot.length; i++) { 
            // 占空间
            if(targetSlot[i] > -1) {
                console.log('右边最近占位', i - solidWidth);
                return i - solidWidth;
            }
        }

        console.log('右边最近占位', slotSize);
        return slotSize - solidWidth;
        
        
    }

    // 位置转时间刻度
    function transToTime(pos){
        // 确定开始时间
        var startPos = pos - 8;
        var hour = Math.trunc(startPos / 60);
        if(hour < 10) {
            hour = '0' + hour;
        }
        // 取开始的分钟
        var min = startPos % 60;
        if(min < 10) {
            min = '0' + min;
        }
        console.log('开始时间' + hour + ':' + min)

    };


 













button[0].addEventListener('click', _ => {
    let list = mondayItemList.map(v => {
        return {
            left: v.offsetLeft,
            width: v.offsetWidth,
        }
    })
    if(list.length > 1){
        list.sort((a,b) => a.left - b.left);
    }
    // console.log(list);
    
})

//const scale = document.querySelector('.scale');
let scaleList = document.getElementsByClassName('scale');
console.log('list trun')
for (i = 0; i < scaleList.length; i++) { 
		console.log('list trun')
        var scale = scaleList[i];
         [...scale.children].forEach((e,index) => {
             console.log(e)
            e.setAttribute('data-number', index)
         })
}



//console.log(scale.children);
//[...scale.children].forEach((e,index) => {
//    console.log(e)
//    e.setAttribute('data-number', index)
//})
/*
const timeTotal = document.querySelector('.timeTotal');
console.log(timeTotal.children);
[...timeTotal.children].forEach((e,index) => {
    console.log(e)
    e.setAttribute('data-number', index)
})*/